package yz.cp.back.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import yz.cp.back.auth.security.SecUser;
import yz.cp.back.auth.security.SecurityUtils;

import java.time.LocalDateTime;
import java.time.ZoneId;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {


    @Override
    public void insertFill(MetaObject metaObject) {
        if(metaObject.hasGetter("createTime")){
            setFieldValByName("createTime", LocalDateTime.now(),metaObject);
        }
        if(metaObject.hasGetter("ctime")){
            setFieldValByName("ctime", Long.valueOf(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().getEpochSecond()).intValue(),metaObject);
        }
        SecUser secUser=SecurityUtils.getSecUser();
        if(metaObject.hasGetter("createBy")&& StringUtils.isNotBlank(secUser.getUsername())){
            setFieldValByName("createBy",secUser.getUsername(),metaObject);
        }
        if(metaObject.hasGetter("cby")&& StringUtils.isNotBlank(secUser.getUsername())){
            setFieldValByName("cby",secUser.getUsername(),metaObject);
        }
        //this.setInsertFieldValByName("operator", "Jerry", metaObject);//@since 快照：3.0.7.2-SNAPSHOT， @since 正式版暂未发布3.0.7
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if(metaObject.hasGetter("param1.updateTime")){
            setFieldValByName("param1.updateTime",LocalDateTime.now(),metaObject);
        }
        if(metaObject.hasGetter("param1.utime")){
            setFieldValByName("param1.utime",Long.valueOf(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().getEpochSecond()).intValue(),metaObject);
        }
        SecUser secUser=SecurityUtils.getSecUser();
        if(metaObject.hasGetter("param1.updateBy")&& StringUtils.isNotBlank(secUser.getUsername())){
            setFieldValByName("param1.updateBy",secUser.getUsername(),metaObject);
        }
        if(metaObject.hasGetter("param1.uby")&& StringUtils.isNotBlank(secUser.getUsername())){
            setFieldValByName("param1.uby",secUser.getUsername(),metaObject);
        }
        //this.setUpdateFieldValByName("operator", "Tom", metaObject);//@since 快照：3.0.7.2-SNAPSHOT， @since 正式版暂未发布3.0.7
    }
}